package com.bookrecomm.service.impl;

import com.bookrecomm.dao.UserRepository;
import com.bookrecomm.entity.Role;
import com.bookrecomm.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户详情服务实现类
 * 用于加载用户信息和权限
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 根据用户名加载用户详情
     * @param username 用户名
     * @return 用户详情
     * @throws UsernameNotFoundException 用户不存在异常
     */
    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("UserDetailsService.loadUserByUsername 被调用，用户名: " + username);
        
        try {
            // 查询用户
            User user = userRepository.findByUsername(username)
                    .orElseThrow(() -> {
                        System.out.println("用户不存在: " + username);
                        return new UsernameNotFoundException("用户不存在: " + username);
                    });
            
            System.out.println("用户存在，ID: " + user.getId() + ", 用户名: " + user.getUsername());
            System.out.println("数据库中的密码: " + user.getPassword());
    
            // 检查用户状态
            if (user.getStatus() == 0) {
                System.out.println("用户已被禁用: " + username);
                throw new UsernameNotFoundException("用户已被禁用: " + username);
            }
    
            // 获取用户权限
            List<GrantedAuthority> authorities = getUserAuthorities(user.getRoles());
            System.out.println("用户角色: " + user.getRoles().stream()
                .map(role -> role.getName())
                .collect(Collectors.joining(", ")));
            System.out.println("用户权限: " + authorities.stream()
                .map(auth -> auth.getAuthority())
                .collect(Collectors.joining(", ")));
    
            // 创建并返回Spring Security的UserDetails对象
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                    user.getUsername(),
                    user.getPassword(),
                    authorities
            );
            
            System.out.println("UserDetails创建成功，用户名: " + userDetails.getUsername());
            System.out.println("UserDetails中的密码: " + userDetails.getPassword());
            
            return userDetails;
        } catch (Exception e) {
            System.out.println("loadUserByUsername方法发生异常: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 获取用户权限
     * @param roles 角色集合
     * @return 权限列表
     */
    private List<GrantedAuthority> getUserAuthorities(Set<Role> roles) {
        return roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getName()))
                .collect(Collectors.toList());
    }
}
